using System;
using System.Collections.Generic;
using System.Text;

namespace BEncode.Types
{
    public class BEString
    {
        private string decValue;
        private string encValue;

        public string DecodedValue
        {
            get { return decValue; }
        }

        public string EncodedValue
        {
            get { return encValue; }
        }

        public BEString():this(string.Empty) { }

        public BEString(string stringvalue)
        {
            if (StringIsEncoded(stringvalue))
            {
                this.decValue = Decode(stringvalue);
                this.encValue = stringvalue;

            }
            else
            {
                this.decValue = stringvalue;
                this.encValue = Encode(stringvalue);
            }
        }

        public static string Encode(string string2encode)
        {
            StringBuilder stringb = new StringBuilder(string2encode.Length.ToString());
            stringb.Append(':').Append(string2encode);
            return stringb.ToString();
        }

        public static string Decode(string string2decode)
        {
            string rtn = string.Empty;

            if (StringIsEncoded(string2decode))
            {
                rtn = string2decode.Substring(string2decode.IndexOf(':'));
            }
            else
            {
                throw new Exception("String is not encoded!");
            }

            return rtn;
        }
        private static bool StringIsEncoded(string string2parse)
        {
            bool rtn = false;

            if (string2parse != string.Empty)
            {
                if (string2parse.Length > 2)
                {
                    if (string2parse.Contains(":"))
                    {
                        for (int i = 0; i < string2parse.IndexOf(':'); i++)
                        {
                            if (Helper.IsNumeric( string2parse[i]))
                            {
                                rtn = true;
                            }
                            else
                            {
                                rtn = false;
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                throw new Exception("String is empty!");
            }
            return rtn;
        }

    }
}
